#include <stdio.h>  /* defines FILENAME_MAX */
#include <string.h>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#include <direct.h>
#define MAX_KEY_LENGTH 255
#define MAX_VALUE_NAME 16383
#else
#include <unistd.h>
#include <limits.h>
#endif // _WIN32

char CurrentExePath[FILENAME_MAX];

void GetCurrentExePath(char *CurrentExePath, size_t length)
{
#ifdef _WIN32
    GetModuleFileName(NULL, CurrentExePath, length);
    /* or GetModuleFileName(NULL, CurrentExePath, length); */
#else
    readlink("/proc/self/exe", CurrentExePath, length);
#endif // _WIN32
}

int IsSelfStartup()
{
    HKEY hkey;
    TCHAR data[MAX_KEY_LENGTH];
    unsigned long datalen = MAX_KEY_LENGTH;
    unsigned long datatype;

    long ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &hkey);

    if(ERROR_SUCCESS == ret)
    {
        ret = RegQueryValueExA(hkey,"IAStorIcon", NULL, &datatype, data, &datalen);
        if(ERROR_SUCCESS == ret)
        {
            printf("%s\n", data);
        }
    }
    RegCloseKey(hkey);
}

int SetSelfStartup()
{
    HKEY hkey;
    TCHAR data[MAX_KEY_LENGTH];
    unsigned long datalen = MAX_KEY_LENGTH;
    unsigned long datatype;

    long ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ | KEY_WRITE, &hkey);
    printf("\"sg11ethgrth\"\n");
    if(ERROR_SUCCESS == ret)
    {
        printf("\"sgethgrth\"\n");
        ret = RegSetValueExA(hkey,"PearCDN", NULL, REG_SZ, data, strlen(data) + 1);
        if(ERROR_SUCCESS == ret)
        {
            printf("%s\n", data);
        }
    }
    RegCloseKey(hkey);
}

void RunSelfAsAdmin()
{
    GetCurrentExePath(CurrentExePath, FILENAME_MAX);
    //char cmd[FILENAME_MAX];
    //snprintf(cmd, FILENAME_MAX, "%s %s", CurrentExePath, "Pear");
    if (ShellExecute(0, "runas", CurrentExePath, "Pear", "C:\\Windows\\System32", SW_NORMAL))
        exit(0);
}

int main(int argc, char **argv)
{
    printf("%d\n", argc);
    if (argc > 1)
    {
        if (strcmp(argv[1], "Pear") == 0)
        {
            GetCurrentExePath(CurrentExePath, FILENAME_MAX);
            printf ("The current working directory is %s\n", CurrentExePath);
            IsSelfStartup();
            SetSelfStartup();
            system("pause");
            return 0;
        }
    }
    RunSelfAsAdmin();
    return 0;
}
